import 'package:flutter/material.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:google_fonts/google_fonts.dart';
// ignore: unused_import
import 'package:raze/potions/raze_constant.dart'; // 用于示例代码引用

/// 空间魔法 - 布局与样式扩展工具
/// 提供了一系列扩展方法来简化布局、样式设置和交互效果
///
/// 使用示例：
/// ```dart
/// // 1. 创建间距 - 使用数值扩展
/// Column(
///   children: [
///     Text('Title'),
///     16.h.boxHeight,      // 垂直间距 16
///     Text('Content'),
///     20.w.boxWidth,       // 水平间距 20
///     30.sp.boxSquare,     // 30x30 的正方形间距
///   ],
/// )
///
/// // 2. 设置边距 - 使用 Widget 包装扩展
/// Text('Hello')
///   .enshroudAll(16.w)           // 所有方向 16 的内边距
///   .enshroudHorizontal(20.w)    // 左右 20 的内边距
///   .enshroudVertical(12.h)      // 上下 12 的内边距
///   .enshroudTop(8.h)            // 仅顶部 8 的内边距
///   .enshroudBottom(8.h)         // 仅底部 8 的内边距
///   .enshroudLeft(16.w)          // 仅左侧 16 的内边距
///   .enshroudRight(16.w)         // 仅右侧 16 的内边距
///
/// // 3. 设置文字样式 - 使用文字扩展
/// Text('Welcome')
///   .applyTypeSize(24.sp)              // 字体大小 24
///   .applyTypeColor(RazeConstants.blue) // 文字颜色
///   .applyNotoSans()                   // Noto Sans 字体
///
/// Text('Title')
///   .applyTypeSize(32.sp)
///   .applyTypeColor(RazeConstants.white)
///   .applyCarterOne(weight: FontWeight.bold) // CarterOne 粗体
///
/// // 4. 链式调用组合使用
/// Text('Beautiful Text')
///   .applyTypeSize(18.sp)
///   .applyTypeColor(RazeConstants.blue)
///   .applyNotoSans(weight: FontWeight.w600)
///   .enshroudAll(16.w)
///   .enshroudHorizontal(24.w)
///
/// // 5. 添加点击效果
/// Container(...)
///   .withTouchResonance(
///     onTap: () => print('Tapped!'),
///     scaleFactor: 0.95,
///   )
///
/// Container(...)
///   .withSubtleTouch(onTap: () => handleTap())    // 轻微效果（98%）
///   .withPronouncedTouch(onTap: () => handleTap()) // 明显效果（92%）
/// ```

/// 数值扩展 - 创建间距盒子
extension SpatialBoxExtension on num {
  /// 创建宽度间距盒子
  Widget get boxWidth => SizedBox(width: w);

  /// 创建高度间距盒子
  Widget get boxHeight => SizedBox(height: h);

  /// 创建正方形间距盒子
  Widget get boxSquare => SizedBox(width: w, height: h);
}

/// Widget扩展 - 边距包装
extension WidgetEnshroudExtension on Widget {
  /// 设置所有方向边距
  Widget enshroudAll(double value) =>
      Padding(padding: EdgeInsets.all(value), child: this);

  /// 设置水平方向边距
  Widget enshroudHorizontal(double value) =>
      Padding(padding: EdgeInsets.symmetric(horizontal: value), child: this);

  /// 设置垂直方向边距
  Widget enshroudVertical(double value) =>
      Padding(padding: EdgeInsets.symmetric(vertical: value), child: this);

  /// 设置左侧边距
  Widget enshroudLeft(double value) =>
      Padding(padding: EdgeInsets.only(left: value), child: this);

  /// 设置右侧边距
  Widget enshroudRight(double value) =>
      Padding(padding: EdgeInsets.only(right: value), child: this);

  /// 设置顶部边距
  Widget enshroudTop(double value) =>
      Padding(padding: EdgeInsets.only(top: value), child: this);

  /// 设置底部边距
  Widget enshroudBottom(double value) =>
      Padding(padding: EdgeInsets.only(bottom: value), child: this);
}

/// 文字样式扩展 - 针对 Text Widget
extension WidgetTypeExtension on Widget {
  /// 应用字体大小
  Widget applyTypeSize(double size) {
    if (this is Text) {
      final text = this as Text;
      return _buildTextWithStyle(
        text,
        text.style?.copyWith(fontSize: size) ?? TextStyle(fontSize: size),
      );
    }
    return this;
  }

  /// 应用文字颜色
  Widget applyTypeColor(Color color) {
    if (this is Text) {
      final text = this as Text;
      return _buildTextWithStyle(
        text,
        text.style?.copyWith(color: color) ?? TextStyle(color: color),
      );
    }
    return this;
  }

  /// 应用 Noto Sans 字体
  Widget applyNotoSans({FontWeight? weight, List<Shadow>? shadows}) {
    if (this is Text) {
      final text = this as Text;
      final fontStyle = GoogleFonts.notoSansSc(
        fontSize: text.style?.fontSize,
        fontWeight: weight ?? text.style?.fontWeight ?? FontWeight.normal,
        color: text.style?.color,
        shadows: shadows ?? text.style?.shadows,
      );
      return _buildTextWithStyle(text, fontStyle.merge(text.style));
    }
    return this;
  }

  /// 应用 CarterOne 字体（装饰性字体）
  Widget applyBagelFatOne({FontWeight? weight, List<Shadow>? shadows}) {
    if (this is Text) {
      final text = this as Text;
      final fontStyle = GoogleFonts.bagelFatOne(
        fontSize: text.style?.fontSize,
        fontWeight: weight ?? text.style?.fontWeight ?? FontWeight.normal,
        color: text.style?.color,
        shadows: shadows ?? text.style?.shadows,
      );
      return _buildTextWithStyle(text, fontStyle.merge(text.style));
    }
    return this;
  }

  /// 内部方法：构建 Text Widget，保留所有原有属性
  Widget _buildTextWithStyle(Text text, TextStyle style) {
    return Text(
      text.data ?? '',
      style: style,
      textAlign: text.textAlign,
      textDirection: text.textDirection,
      locale: text.locale,
      softWrap: text.softWrap,
      overflow: text.overflow,
      textScaleFactor: text.textScaleFactor,
      maxLines: text.maxLines,
      semanticsLabel: text.semanticsLabel,
      textWidthBasis: text.textWidthBasis,
      textHeightBehavior: text.textHeightBehavior,
      selectionColor: text.selectionColor,
    );
  }
}

/// Widget扩展 - 触摸交互效果
extension WidgetTouchResonanceExtension on Widget {
  /// 添加触摸缩放效果 - 提供视觉反馈
  ///
  /// [onTap] 点击回调函数
  /// [scaleFactor] 缩放比例，默认 0.96（缩小到96%）
  /// [duration] 动画持续时间，默认 150 毫秒
  /// [curve] 动画曲线，默认 Curves.easeOut
  Widget withTouchResonance({
    required VoidCallback? onTap,
    double scaleFactor = 0.96,
    Duration? duration,
    Curve? curve,
  }) {
    return _TouchResonanceWidget(
      onTap: onTap,
      scaleFactor: scaleFactor,
      duration: duration ?? const Duration(milliseconds: 150),
      curve: curve ?? Curves.easeOut,
      child: this,
    );
  }

  /// 轻微触摸效果（缩放到 98%）
  Widget withSubtleTouch(VoidCallback? onTap) {
    return withTouchResonance(onTap: onTap, scaleFactor: 0.98);
  }

  /// 明显触摸效果（缩放到 92%）
  Widget withPronouncedTouch(VoidCallback? onTap) {
    return withTouchResonance(onTap: onTap, scaleFactor: 0.92);
  }
}

/// 触摸共振效果组件 - 内部实现类
class _TouchResonanceWidget extends StatefulWidget {
  final Widget child;
  final VoidCallback? onTap;
  final double scaleFactor;
  final Duration duration;
  final Curve curve;

  const _TouchResonanceWidget({
    required this.child,
    required this.onTap,
    required this.scaleFactor,
    required this.duration,
    required this.curve,
  });

  @override
  State<_TouchResonanceWidget> createState() => _TouchResonanceWidgetState();
}

class _TouchResonanceWidgetState extends State<_TouchResonanceWidget>
    with SingleTickerProviderStateMixin {
  late AnimationController _controller;
  late Animation<double> _scaleAnimation;
  bool _isPressed = false;

  @override
  void initState() {
    super.initState();
    _controller = AnimationController(vsync: this, duration: widget.duration);
    _scaleAnimation = Tween<double>(
      begin: 1.0,
      end: widget.scaleFactor,
    ).animate(CurvedAnimation(parent: _controller, curve: widget.curve));
  }

  @override
  void dispose() {
    _controller.dispose();
    super.dispose();
  }

  void _handleTapDown(TapDownDetails details) {
    if (widget.onTap != null) {
      setState(() => _isPressed = true);
      _controller.forward();
    }
  }

  void _handleTapUp(TapUpDetails details) {
    if (_isPressed) {
      setState(() => _isPressed = false);
      _controller.reverse().then((_) {
        widget.onTap?.call();
      });
    }
  }

  void _handleTapCancel() {
    if (_isPressed) {
      setState(() => _isPressed = false);
      _controller.reverse();
    }
  }

  @override
  Widget build(BuildContext context) {
    return GestureDetector(
      onTapDown: _handleTapDown,
      onTapUp: _handleTapUp,
      onTapCancel: _handleTapCancel,
      child: ScaleTransition(scale: _scaleAnimation, child: widget.child),
    );
  }
}

/// Widget扩展 - 边框阴影效果
extension WidgetBorderShadowExtension on Widget {
  /// 添加右边框和下边框阴影效果
  /// 使右边框和下边框看起来更厚，用于创建3D视觉效果的按钮
  /// [shadowColor] 阴影颜色，默认为黑色
  /// [thickness] 阴影粗细，默认为1.0（对应1.w的偏移量），数值越大阴影越粗
  Widget withRightBottomShadow({Color? shadowColor, double thickness = 1.0}) {
    final shadowColorFinal = shadowColor ?? RazeConstants.black;
    final thicknessValue = thickness;

    // 如果已经是 Container 且有 decoration，添加 boxShadow
    if (this is Container) {
      final container = this as Container;
      final existingDecoration = container.decoration as BoxDecoration?;

      if (existingDecoration != null) {
        final existingShadows = existingDecoration.boxShadow ?? [];
        // 计算阴影偏移量（基于thickness参数）
        final rightOffset1 = Offset(thicknessValue * 1.w, 0);
        final rightOffset2 = Offset(thicknessValue * 1.w, 0);
        final bottomOffset1 = Offset(0, thicknessValue * 1.w);
        final bottomOffset2 = Offset(0, thicknessValue * 1.w);

        final borderShadows = [
          // 右边框阴影
          BoxShadow(
            color: shadowColorFinal,
            offset: rightOffset1,
            blurRadius: 0,
            spreadRadius: 0,
          ),
          BoxShadow(
            color: shadowColorFinal,
            offset: rightOffset2,
            blurRadius: 0,
            spreadRadius: 0,
          ),
          // 下边框阴影
          BoxShadow(
            color: shadowColorFinal,
            offset: bottomOffset1,
            blurRadius: 0,
            spreadRadius: 0,
          ),
          BoxShadow(
            color: shadowColorFinal,
            offset: bottomOffset2,
            blurRadius: 0,
            spreadRadius: 0,
          ),
          // 右下角额外阴影，使其更厚
          BoxShadow(
            color: shadowColorFinal,
            offset: Offset(thicknessValue * 1.w, thicknessValue * 1.w),
            blurRadius: 0,
            spreadRadius: 0,
          ),
          BoxShadow(
            color: shadowColorFinal,
            offset: Offset(
              thicknessValue * 1.5 * 1.w,
              thicknessValue * 1.5 * 1.w,
            ),
            blurRadius: 0,
            spreadRadius: 0,
          ),
        ];
        final newShadows = [...existingShadows, ...borderShadows];

        return Container(
          key: container.key,
          alignment: container.alignment,
          padding: container.padding,
          color: container.color,
          decoration: existingDecoration.copyWith(boxShadow: newShadows),
          foregroundDecoration: container.foregroundDecoration,
          constraints: container.constraints,
          margin: container.margin,
          transform: container.transform,
          transformAlignment: container.transformAlignment,
          clipBehavior: container.clipBehavior,
          child: container.child,
        );
      } else {
        // Container 但没有 decoration，添加 decoration
        // 计算阴影偏移量（基于thickness参数）
        final rightOffset1 = Offset(thicknessValue * 1.w, 0);
        final rightOffset2 = Offset(thicknessValue * 1.w, 0);
        final bottomOffset1 = Offset(0, thicknessValue * 1.w);
        final bottomOffset2 = Offset(0, thicknessValue * 1.w);

        final borderShadows = [
          // 右边框阴影
          BoxShadow(
            color: shadowColorFinal,
            offset: rightOffset1,
            blurRadius: 0,
            spreadRadius: 0,
          ),
          BoxShadow(
            color: shadowColorFinal,
            offset: rightOffset2,
            blurRadius: 0,
            spreadRadius: 0,
          ),
          // 下边框阴影
          BoxShadow(
            color: shadowColorFinal,
            offset: bottomOffset1,
            blurRadius: 0,
            spreadRadius: 0,
          ),
          BoxShadow(
            color: shadowColorFinal,
            offset: bottomOffset2,
            blurRadius: 0,
            spreadRadius: 0,
          ),
          // 右下角额外阴影，使其更厚
          BoxShadow(
            color: shadowColorFinal,
            offset: Offset(thicknessValue * 1.w, thicknessValue * 1.w),
            blurRadius: 0,
            spreadRadius: 0,
          ),
          BoxShadow(
            color: shadowColorFinal,
            offset: Offset(
              thicknessValue * 1.5 * 1.w,
              thicknessValue * 1.5 * 1.w,
            ),
            blurRadius: 0,
            spreadRadius: 0,
          ),
        ];

        return Container(
          key: container.key,
          alignment: container.alignment,
          padding: container.padding,
          color: container.color,
          decoration: BoxDecoration(boxShadow: borderShadows),
          foregroundDecoration: container.foregroundDecoration,
          constraints: container.constraints,
          margin: container.margin,
          transform: container.transform,
          transformAlignment: container.transformAlignment,
          clipBehavior: container.clipBehavior,
          child: container.child,
        );
      }
    }

    // 不是 Container，用 Container 包装并添加阴影
    // 计算阴影偏移量（基于thickness参数）
    final rightOffset1 = Offset(thicknessValue * 1.w, 0);
    final rightOffset2 = Offset(thicknessValue * 1.w, 0);
    final bottomOffset1 = Offset(0, thicknessValue * 1.w);
    final bottomOffset2 = Offset(0, thicknessValue * 1.w);

    final borderShadows = [
      // 右边框阴影
      BoxShadow(
        color: shadowColorFinal,
        offset: rightOffset1,
        blurRadius: 0,
        spreadRadius: 0,
      ),
      BoxShadow(
        color: shadowColorFinal,
        offset: rightOffset2,
        blurRadius: 0,
        spreadRadius: 0,
      ),
      // 下边框阴影
      BoxShadow(
        color: shadowColorFinal,
        offset: bottomOffset1,
        blurRadius: 0,
        spreadRadius: 0,
      ),
      BoxShadow(
        color: shadowColorFinal,
        offset: bottomOffset2,
        blurRadius: 0,
        spreadRadius: 0,
      ),
    ];

    return Container(
      decoration: BoxDecoration(boxShadow: borderShadows),
      child: this,
    );
  }
}
